import { UserConfigExport, ConfigEnv, loadEnv } from 'vite'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import WindiCSS from 'vite-plugin-windicss'

import VantComponents from 'unplugin-vue-components/vite'

// vant按需引入的插件
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'

import postCssPxToRem from 'postcss-pxtorem'
import autoprefixer from 'autoprefixer'

import basicSsl from "@vitejs/plugin-basic-ssl" // 使用https

import viteImagemin from 'vite-plugin-imagemin' // 打包是图片的压缩

import legacy from '@vitejs/plugin-legacy' 

export default ({ mode }: ConfigEnv): UserConfigExport => {
    const root = process.cwd()
    const env = loadEnv(mode, root) as unknown as ImportMetaEnv
    return {
        resolve: {
            alias: {
                '/@': path.resolve('./src')
            },
            extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'] // 使用路径别名时想要省略的后缀名
        },
        base: '',
        // base: '/policyReviewH5/',
        server: {
            // https: true,
          open: true,
          proxy: {
            "/ocr-api": {
                target: env.VITE_APP_BACKEND_HOST,
                changeOrigin: true,
                secure: false,
                rewrite: (path) => path.replace(`^/ocr-api`, "")
                
              },
              "/system": {
                target: env.VITE_APP_BACKEND_HOST,
                changeOrigin: true,
                secure: false,
                rewrite: (path) => path.replace(`^/system`, "")
                
              },
              "/sms-api": {
                target: env.VITE_APP_BACKEND_HOST,
                changeOrigin: true,
                secure: false,
                rewrite: (path) => path.replace(`^/sms-api`, "")
              },
            [env.VITE_APP_API_BASE_URL]: {
                target: env.VITE_APP_BACKEND_HOST,
                changeOrigin: true,
                secure: false,
                rewrite:(path) => path.replace(`^${env.VITE_APP_API_BASE_URL}`, "")
            }
            },
            port: env.VITE_PORT
        },
        build: {
            outDir: 'iagentH5',
            chunkSizeWarningLimit: 1500,
            manifest: true,
            rollupOptions: {
                output: {
                    manualChunks: {
                        vue: ['vue', 'vue-router'],
                        vant: ['vant']
                    }
                }
            }
        },
        plugins: [
            vue(),
            legacy({
                 targets: ['defaults', 'ie >= 8', 'chrome >= 52', "Android >= 4.1","iOS >= 7.1"], // 需要兼容的目标列表，可以设置多个
                 additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
                 renderLegacyChunks:true,
                 polyfills:[
                'es.symbol',
                'es.array.filter',
                'es.promise',
                'es.promise.finally',
                'es/map',
                'es/set',
                'es.array.for-each',
                'es.object.define-properties',
                'es.object.define-property',
                'es.object.get-own-property-descriptor',
                'es.object.get-own-property-descriptors',
                'es.object.keys',
                'es.object.to-string',
                'web.dom-collections.for-each',
                'esnext.global-this',
                'esnext.string.match-all'
                ]
            }),
            WindiCSS(),
            vueSetupExtend(),
            Components({
                resolvers: [VantResolver()] // 按需引入vant
            }),
            createSvgIconsPlugin({
                // 指定需要缓存的图标文件夹
                iconDirs: [path.resolve(process.cwd(), 'src/icons')],
                // 指定symbolId格式
                symbolId: 'icon-[dir]-[name]'
            }),
            VantComponents({
                // 处理@vant/auto-import-resolver插件对某些组件的样式无法引入 例如：toast弹窗
                resolvers: [VantResolver({
                  importStyle: true,
                })],
            }),
            viteImagemin({
                gifsicle: { // gif图片压缩
                    optimizationLevel: 3, 
                    interlaced: false 
                },
                optipng: { // png
                    optimizationLevel: 7 
                },
                mozjpeg: { // jpeg
                    quality: 20 
                },
                pngquant: { // png
                    quality: [0.8, 0.9], 
                    speed: 4 
                },
                svgo: { // svg压缩
                    plugins: [
                        {
                            name: 'removeViewBox'
                        },
                        {
                            name: 'removeEmptyAttrs',
                            active: false
                        }
                    ]
                }
            })
          // basicSsl()
        ],
        css: {
            postcss: { 
                plugins: [
                    postCssPxToRem({ // 自适应，px>rem转换
                        rootValue: 16, // 1rem的大小
                        // rootValue: 37.5, // 1rem的大小
                        propList: ['*'] // 需要转换的属性，这里选择全部都进行转换
                    }),
                    autoprefixer({ // 自动添加前缀
                        overrideBrowserslist: [
                            "Android 4.1",
                            "iOS 7.1",
                            "Chrome > 31",
                            "ff > 31",
                            "ie >= 8"
                            // 'last 2 versions', // 所有主流浏览器最近2个版本
                        ],
                        grid: true
                    })
                ]
            },
            preprocessorOptions: {
                less: {
                    charset: false,
                    additionalData: `@import "${path.resolve(__dirname,"./src/styles/variable.less")}";`
                }
            }
        }
    }
}
